package com.axing.xingxianggateway;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.axing.model.entity.InterfaceInfo;
import com.axing.model.entity.User;
import com.axing.service.InnerInterfaceInfoService;
import com.axing.service.InnerUserInterfaceInfoService;
import com.axing.service.InnerUserService;
import com.axing.xingxiangclientsdk.utils.SignUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 全局过滤
 *
 */
@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserInterfaceInfoService  innerUserInterfaceInfoService;

    private static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1");

    private final WebExceptionHandler responseStatusExceptionHandler;

    public static final String INTERFACE_HOST="http://localhost:8090";

    public CustomGlobalFilter(WebExceptionHandler responseStatusExceptionHandler) {
        this.responseStatusExceptionHandler = responseStatusExceptionHandler;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //2. 日志 http://localhost:8090/api/name/user/
        ServerHttpRequest request = exchange.getRequest();
        String method = request.getMethod().toString();
        String url = INTERFACE_HOST +request.getPath().value();
        log.info("请求唯一标识" + request.getId());
        log.info("请求路径" + url);
        log.info("请求方法" + method);
        log.info("请求参数" + request.getQueryParams());
        log.info("请求来源地址" + request.getRemoteAddress());
        String sourceAddress = request.getLocalAddress().getHostString();
        log.info("请求来源地址" + sourceAddress);
        log.info("请求来源地址" + request.getRemoteAddress());
        //3. 黑白名单  http://127.0.0.1:8090/api/name/?name=ffffdasfasd
        ServerHttpResponse response = exchange.getResponse();
        if(!IP_WHITE_LIST.contains(sourceAddress)){
          return  handleNoAuth(response);
        }
        //4. 用户鉴权 判断ak sk是否合法
        HttpHeaders headers = request.getHeaders();
        String accessKey = headers.getFirst("accessKey");
        String nonce = headers.getFirst("nonce");
        String timestamp = headers.getFirst("timestamp");
        String sign = headers.getFirst("sign");
        String body = headers.getFirst("body");
        //  实际情况在数据库中查
        User invokeUser =null;
        InterfaceInfo interfaceInfo = null;

        try{
            invokeUser = innerUserService.getInvokeUser(accessKey);
        }catch (Exception e){
            log.error("用户异常");
        }
        if(invokeUser == null){
            handleNoAuth(response);
        }

      /*  if(!accessKey.equals("axing")) {
            throw new RuntimeException("无权限");
        }*/
        if (Long.parseLong(nonce) > 10000) {
            throw new RuntimeException("无权限");
        }
        //时间不能超过五分钟
        long currentTime = System.currentTimeMillis() / 1000;
        final long FIVE_MINUTES = 60 * 5L;
        if(currentTime - java.lang.Long.parseLong(timestamp) >=FIVE_MINUTES) {
            return  handleNoAuth(response);
        }
        //  secretKey 应该从数据库中拿取
        String secretKey = invokeUser.getSecretKey();
        String serverSign = SignUtils.genSign(body,secretKey);
        if(sign ==null  ||!sign.equals(serverSign)) {
            throw new RuntimeException("无权限");
        }
        //5. 请求的模拟接口是否存在
        //  从数据库中查询模拟接口是否存在，以及请求方法是否匹配  还可以校验参数    远程调用
        try{
            interfaceInfo   =  innerInterfaceInfoService.getInterfaceInfo(url, method);
        }catch (Exception e){
            log.error("interface exception ");
        }
        if(interfaceInfo == null){
            handleNoAuth(response);
        }
        //请求转发 调用模拟接口 + 相应日志
        return responseLog(exchange,chain,interfaceInfo.getId(),invokeUser.getId());

    }


    public Mono<Void> responseLog(ServerWebExchange exchange, GatewayFilterChain chain ,Long interfaceInfoId , long userId ) {
        try {
            ServerHttpResponse originalResponse = exchange.getResponse();
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            HttpStatus statusCode = originalResponse.getStatusCode();
            if (statusCode != HttpStatus.OK) {
                return chain.filter(exchange);//降级处理返回数据
            }
            ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                //该方法是调用目标接口方法后 在调用
                @Override
                public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                    if (body instanceof Flux) {
                        Flux<? extends DataBuffer> fluxBody = Flux.from(body);

                        return super.writeWith(fluxBody.buffer().map(dataBuffers -> {


                            // 合并多个流集合，解决返回体分段传输
                            DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                            DataBuffer buff = dataBufferFactory.join(dataBuffers);
                            byte[] content = new byte[buff.readableByteCount()];
                            buff.read(content);
                            DataBufferUtils.release(buff);//释放掉内存


                            //7. todo 调用成功 接口调用次数 + 1

                            try{
                            innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                            } catch (Exception e) {
                                log.error("invokeCount exception ");
                            }

                            // 响应日志
                            log.info("响应日志:" + new String(content));
                            //8. 调用失败 返回一个规范的错误码
                            if (originalResponse.getStatusCode() != HttpStatus.OK) {
                                handleInvokeError(originalResponse);
                            }


                            //排除Excel导出，不是application/json不打印。若请求是上传图片则在最上面判断。
                                MediaType contentType = originalResponse.getHeaders().getContentType();
                            if (!MediaType.APPLICATION_JSON.isCompatibleWith(contentType)) {
                                return bufferFactory.wrap(content);
                            }

                            // 构建返回日志  如果响应的是application/json格式才 打印日志
                            String joinData = new String(content);
                            String result = modifyBody(joinData);
                            List<Object> rspArgs = new ArrayList<>();
                            rspArgs.add(originalResponse.getStatusCode().value());
                            rspArgs.add(exchange.getRequest().getURI());
                            rspArgs.add(result);
                            log.info("<-- {} {}\n{}", rspArgs.toArray());


                            getDelegate().getHeaders().setContentLength(result.getBytes().length);
                            return bufferFactory.wrap(result.getBytes());
                        }));
                    } else {
                        log.error("<-- {} 响应code异常", getStatusCode());
                    }
                    return super.writeWith(body);
                }
            };
            return chain.filter(exchange.mutate().response(decoratedResponse).build());

        } catch (Exception e) {
            log.error("gateway log exception.\n" + e);
            return chain.filter(exchange);
        }
    }

    //返回统一的JSON日期数据 2024-02-23 11:00， null转空字符串
    private String modifyBody(String jsonStr){
        com.alibaba.fastjson.JSONObject json = JSON.parseObject(jsonStr, Feature.AllowISO8601DateFormat);
        com.alibaba.fastjson.JSONObject.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm";
        return com.alibaba.fastjson.JSONObject.toJSONString(json, (ValueFilter) (object, name, value) -> value == null ? "" : value, SerializerFeature.WriteDateUseDateFormat);
    }


    @Override
    public int getOrder() {
        return -1;
    }


    public Mono<Void> handleNoAuth(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return   response.setComplete();
    }


    public  Mono<Void> handleInvokeError(ServerHttpResponse response) {
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return   response.setComplete();
    }

}